import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { GenerationCard } from '../components';
import gsap from 'gsap';
import './Inspiration.css';

// 将 designProjects 移到组件外部，避免每次渲染都重新创建
const designProjects = [
  {
    id: 1,
    title: "星动健身中心",
    category: "运动空间",
    area: "800㎡",
    designer: "张设计师",
    description: "现代工业风健身空间,采用AI智能布局优化,提升空间利用率35%",
    tags: ["工业风格", "AI布局优化", "智能照明"],
    image: "https://picsum.photos/400/300?random=1"
  },
  {
    id: 2,
    title: "云端咖啡厅",
    category: "餐饮空间",
    area: "200㎡",
    designer: "李设计师",
    description: "北欧简约风格咖啡厅,通过AI色彩搭配,营造温馨舒适的用餐氛围",
    tags: ["北欧风格", "AI色彩搭配", "氛围营造"],
    image: "https://picsum.photos/400/300?random=2"
  },
  {
    id: 3,
    title: "悦美SPA会所",
    category: "美业空间",
    area: "500㎡",
    designer: "王设计师",
    description: "奢华典雅的美容会所设计,运用AI材质推荐,打造极致的视觉体验",
    tags: ["奢华风格", "AI材质推荐", "视觉体验"],
    image: "https://picsum.photos/400/300?random=3"
  },
  {
    id: 4,
    title: "智慧办公空间",
    category: "办公空间",
    area: "1200㎡",
    designer: "陈设计师",
    description: "现代科技感办公环境,集成AI智能系统,提升工作效率40%",
    tags: ["现代科技", "AI智能系统", "效率提升"],
    image: "https://picsum.photos/400/300?random=4"
  },
  {
    id: 5,
    title: "儿童教育中心",
    category: "教育空间",
    area: "600㎡",
    designer: "刘设计师",
    description: "创意互动式学习空间,运用AI个性化设计,激发儿童学习兴趣",
    tags: ["创意互动", "AI个性化", "学习兴趣"],
    image: "https://picsum.photos/400/300?random=5"
  },
  {
    id: 6,
    title: "精品酒店大堂",
    category: "酒店空间",
    area: "300㎡",
    designer: "赵设计师",
    description: "高端商务酒店大堂,融合传统与现代元素,营造尊贵体验",
    tags: ["高端商务", "传统现代", "尊贵体验"],
    image: "https://picsum.photos/400/300?random=6"
  },
  {
    id: 7,
    title: "艺术画廊",
    category: "文化空间",
    area: "400㎡",
    designer: "孙设计师",
    description: "当代艺术展示空间,运用AI光影设计,突出艺术品视觉效果",
    tags: ["当代艺术", "AI光影设计", "视觉效果"],
    image: "https://picsum.photos/400/300?random=7"
  },
  {
    id: 8,
    title: "医疗康复中心",
    category: "医疗空间",
    area: "700㎡",
    designer: "周设计师",
    description: "温馨舒适的康复环境,通过AI环境优化,促进患者康复进程",
    tags: ["温馨舒适", "AI环境优化", "康复促进"],
    image: "https://picsum.photos/400/300?random=8"
  }
];

const Inspiration: React.FC = () => {
  const navigate = useNavigate();
  const [prompt] = useState("");
  const [activeType, setActiveType] = useState<
    "image" | "video" | "migration" | "digital" | "action"
  >("image");
  const [selectedBusiness, setSelectedBusiness] = useState<string>("业态选择");
  const [selectedFeature, setSelectedFeature] = useState<string>("展开功能");
  const [uploadedImage, setUploadedImage] = useState<string | null>(null);
  const [referenceImage, setReferenceImage] = useState<string | null>(null);
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const gridRef = useRef<HTMLDivElement>(null);

  // 处理图片上传
  const handleImageUpload = (imageUrl: string | null, file?: File) => {
    if (imageUrl) {
      console.log('原图已上传:', imageUrl);
      setUploadedImage(imageUrl);
    }
    if (file) {
      console.log('原图文件已上传:', file);
      setUploadedFile(file);
    }
  };

  // 处理参考图上传
  const handleReferenceImageUpload = (imageUrl: string | null) => {
    if (imageUrl) {
      console.log('参考图已上传:', imageUrl);
      setReferenceImage(imageUrl);
    }
  };

  // 处理生成按钮点击
  const handleGenerate = async (params?: { noiseLevel?: string; atmosphere?: string; referenceFile?: File; referenceImageUrl?: string; prompt?: string }) => {
    // 使用传入的 prompt 参数或内部状态
    const finalPrompt = params?.prompt || prompt;
    
    // 使用传入的参考图或内部状态
    const finalReferenceImage = params?.referenceImageUrl || referenceImage;
    
    const generateState = {
      prompt: finalPrompt.trim() || "请生成一张图片",
      activeType: activeType,
      selectedFeature: selectedFeature,
      selectedBusiness: selectedBusiness,
      uploadedImage: uploadedImage,
      referenceImage: finalReferenceImage,
      uploadedFile: uploadedFile,
      noiseLevel: params?.noiseLevel,
      atmosphere: params?.atmosphere
    };
    
    console.log('跳转到生成页面，状态:', generateState);
    console.log('参考图状态:', {
      referenceImage: referenceImage,
      finalReferenceImage: finalReferenceImage,
      paramsReferenceImageUrl: params?.referenceImageUrl
    });
    navigate('/generate', { state: generateState });
  };


  // GSAP 入场动画
  useEffect(() => {
    const cards = document.querySelectorAll('.design-card');
    
    if (cards.length === 0) return;
    
    // 设置初始状态
    gsap.set(cards, {
      opacity: 0,
      y: 60,
      scale: 0.9
    });
    
    // 创建时间线动画
    const tl = gsap.timeline();
    
    // 为每个卡片添加动画
    cards.forEach((card, index) => {
      tl.to(card, {
        opacity: 1,
        y: 0,
        scale: 1,
        duration: 0.8,
        ease: "back.out(1.7)",
        delay: index * 0.15
      }, index * 0.1);
    });
    
    // 添加整体淡入效果
    tl.fromTo('.discovery-section', 
      { opacity: 0 },
      { opacity: 1, duration: 0.6, ease: "power2.out" },
      0
    );
    
  }, []); // 只在组件挂载时执行一次

  // 卡片悬停动画
  useEffect(() => {
    const cards = document.querySelectorAll('.design-card');
    
    cards.forEach((card) => {
      const handleMouseEnter = () => {
        gsap.to(card, {
          scale: 1.05,
          y: -8,
          duration: 0.3,
          ease: "power2.out"
        });
      };
      
      const handleMouseLeave = () => {
        gsap.to(card, {
          scale: 1,
          y: 0,
          duration: 0.3,
          ease: "power2.out"
        });
      };
      
      card.addEventListener('mouseenter', handleMouseEnter);
      card.addEventListener('mouseleave', handleMouseLeave);
      
      return () => {
        card.removeEventListener('mouseenter', handleMouseEnter);
        card.removeEventListener('mouseleave', handleMouseLeave);
      };
    });
  }, []); // 只在组件挂载时执行一次

  return (
    <main className="main-content">
      {/* 主内容区域 - 内部滚动 */}
      <div className="inspiration-main">
        {/* Generation Section using GenerationCard component */}
        <div>
        <GenerationCard
          activeType={activeType}
          setActiveType={setActiveType}
          selectedFeature={selectedFeature}
          setSelectedFeature={setSelectedFeature}
          selectedBusiness={selectedBusiness}
          setSelectedBusiness={setSelectedBusiness}
          onGenerate={handleGenerate}
          onImageUpload={handleImageUpload}
          onReferenceImageUpload={handleReferenceImageUpload}
          uploadedImage={uploadedImage}
          referenceImage={referenceImage}
          position="center"
          width="1440px"
        />
        </div>
        {/* Discovery Section */}
        <section className="discovery-section">
        {/* <div className="discovery-header">
          <NavTabs
            items={tabItems}
            activeTab={activeTab}
            onTabChange={setActiveTab}
            variant="pills"
            size="medium"
          />
          <div className="discovery-actions">
            <div className="search-wrapper">
              <input
                type="text"
                placeholder="nba手办"
                className="search-input"
              />
              <span className="search-icon">
              <svg width="1em" height="1em" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" fill="none" role="presentation" xmlns="http://www.w3.org/2000/svg" class=""><g><path data-follow-fill="currentColor" d="M4.563 10.75a6.5 6.5 0 1 1 13 0 6.5 6.5 0 0 1-13 0Zm6.5-8.5a8.5 8.5 0 1 0 5.261 15.176l3.406 3.406a1 1 0 0 0 1.415-1.414l-3.407-3.406A8.5 8.5 0 0 0 11.062 2.25Z" clip-rule="evenodd" fill-rule="evenodd" fill="currentColor"></path></g></svg>
              </span>
            </div>
          </div>
        </div> */}

        <div className="design-grid" ref={gridRef}>
          {designProjects.map((project) => (
            <div key={project.id} className="design-card">
              <div className="card-image-container">
                <img
                  src={project.image}
                  alt={project.title}
                  className="card-image"
                />
                <div className="category-tag">{project.category}</div>
              </div>
              
              <div className="card-content">
                <h3 className="card-title">{project.title}</h3>
                <div className="card-meta">
                  <span className="card-area">{project.area}</span>
                  <span className="card-designer">{project.designer}</span>
                </div>
                <p className="card-description">{project.description}</p>
                <div className="card-tags">
                  {project.tags.map((tag, index) => (
                    <span key={index} className="tag">{tag}</span>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>
        </section>
      </div>
    </main>
  );
};

export default Inspiration;
